<template>
	<view class="container">
		<custom-header :isHomepage="false"></custom-header>
		<text class="page-title">充值永恒币</text>

		<view class="main-content">

			<view class="account-balance">
				<text>账号:</text>
				<text class="phone-number">{{ userInfo?.account || 'N/A' }}</text>
				<text>永恒币:</text>
				<text class="tianbi-balance">{{ userInfo?.user_coin || '0' }}</text>
				<text class="tianbi-explain" @click="handleTianbiExplain">(永恒币说明)</text>
			</view>

			<view class="recharge-options-label">选择充值永恒币数量:</view>
			<view class="recharge-options-grid">
				<view class="recharge-option" v-for="(option, index) in rechargeOptions" :key="index"
					:class="{ selected: selectedOptionIndex === option.type }" @click="selectRechargeOption(option.type)">
					<text class="option-main">{{ option.coin }}永恒币, {{ option.price }}元</text>
					<text class="option-bonus" v-if="option.trip != ''">({{ option.trip }})</text>
				</view>
			</view>

			<view class="payment-method-label">选择支付方式:</view>
			<view class="payment-methods">
				<view class="payment-method-item" :class="{ selected: selectedPaymentMethod === 2 }"
					@click="selectPaymentMethod(2)">
					<image class="payment-icon" src="/static/wechatpay-icon.png" mode="aspectFit"></image>
					<text class="payment-text">微信支付</text>
				</view>
			</view>

			<button class="confirm-recharge-button" @click="handleConfirmRecharge">确认充值支付</button>

		</view>

		<view class="explanation-section">
			<text class="explanation-title">说明:</text>
			<text class="explanation-text">1、"永恒币"即"天堂币"，用于网上墓园敬献祭品、扫墓等用途。</text>
			<text class="explanation-text">2、永恒币兑换后无法退回。</text>
			<text class="explanation-text">3、永恒币不能用于升级纪念馆，升级纪念馆请前往“管理纪念馆”栏目升级。</text>
		</view>
		<Footer></Footer>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		toRaw
	} from 'vue';
	import { onLoad } from '@dcloudio/uni-app'
	import CustomHeader from '@/components/header/index.vue'; // Adjust path as needed
	import Footer from '@/components/footer/index.vue'
	import { apiRechargeCreate, apiRechargeCoin_config, apiPayPrepay } from '@/api/pay';
	import wx from 'weixin-js-sdk';
	import { login, getUserInfo, logout, scanLogin, oaLogin } from '@/api/user.js';
	import { setToken } from '@/utils/token.js';
	const userInfo = ref()
	
	
	const rechargeOptions = ref([]);

	const selectedOptionIndex = ref(); // 充值项

	const selectedPaymentMethod = ref(2); // 充值方式

	// 获取永恒币充值配置
	const getTianBiConfig = () => {
		apiRechargeCoin_config().then((res) => {
			console.log(res)
			rechargeOptions.value = res.data
			selectedOptionIndex.value = res.data && res.data.length > 0 ? res.data[0].type : ''
		})
	}

	
	
	





	const selectRechargeOption = (index) => {
		selectedOptionIndex.value = index;
		console.log('Selected recharge option:', rechargeOptions.value[index]);
	}

	const selectPaymentMethod = (method) => {
		selectedPaymentMethod.value = method;
		console.log('Selected payment method:', method);
	}

	const handleTianbiExplain = () => {
		console.log('Go to Tianbi explanation page');
		// uni.navigateTo({ url: '/pages/tianbi_explain/tianbi_explain' }); // Replace with actual path
	}
	const payInfo = ref()
	const selectedOption = ref()
	const getQueryVariable = (variable) => {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return (false);
	}
	const toLog = () => {
		// return
		let code = getQueryVariable('code')
		if (code) {
			console.log(code);
			oaLogin({code}).then(res=>{
				console.log(res)
				if(res.code == 1){
					setToken(res.data.token)
					uni.setStorageSync('userInfo', res.data)
					uni.setStorageSync('user_id', res.data.id)
					userInfo.value = res.data
					user_id.value = res.data.id
				}
			}).catch(error=>{
				console.log(error)
			})
		} else {
			console.log('111111111111111111111111111111')
			let appid = "wx36819d0881150fc8" //项目appid
			let mainstate = Math.random()
			let url = encodeURIComponent('https://cqjsyh.com/H5/pages/graveyardManage/payInfo/index') //这里的是回调地址要与申请的地址填写一致
			let scopes = "snsapi_userinfo" //表示授权的作用域，多个可以用逗号隔开，snsapi_base表示静默授权，snsapi_userinfo表示非静默授权
			let httpsUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=${scopes}&state=${mainstate}&connect_redirect=1#wechat_redirect`
			window.location.href = httpsUrl
		}
	}
	// 确认支付
	const handleConfirmRecharge = () => {
		// 这里判断当前环境是否是微信浏览器
		if (!window.navigator.userAgent.match(/MicroMessenger/i)) {
			alert('请在微信浏览器中打开！');
			return;
		}
		if(userInfo.value.has_h5_auth === false){
			toLog()
			return
		}
		if (!selectedOptionIndex.value) {
			alert('请选择充值数量！');
			return;
		}
		if (!selectedPaymentMethod.value) {
			alert('请选择支付方式！');
			return;
		}
		console.log(toRaw(rechargeOptions.value), toRaw(selectedOptionIndex.value), toRaw(selectedPaymentMethod.value))
		selectedOption.value = rechargeOptions.value.find(opt => opt.type === selectedOptionIndex.value);
		console.log(`确认充值: ${selectedOption.value?.coin} 永恒币 (${selectedOption.value?.price}元), 支付方式: ${selectedPaymentMethod.value}`);
		// alert('确认充值 (模拟)');
		let obj = {
			type: '2',
			coin_type: Number(selectedOptionIndex.value),
			pay_way: selectedPaymentMethod.value,
		}
		apiRechargeCreate(obj).then((res) => {
			console.log(res)
			
			// uni.showToast({
			// 	title:'进入了接口'
			// })
			apiPayPrepay({
				terminal: 2,
				order_id: res.data.order_id,
				pay_way: selectedPaymentMethod.value,
			}).then( async (result) => {
				console.log(result)
				
				// uni.showModal({
				// 	title:'提示',
				// 	content: `${JSON.stringify(result)}`
				// })
				// uni.showToast({
				// 	title: `${JSON.stringify(result)}`
				// })
				if(result.code == 1){
					wx.config({
					  	debug: false,
					  	appId: result.data.config.appId,
					  	timestamp: result.data.config.timeStamp || "",
					  	nonceStr: result.data.config.nonceStr || "",
					  	signature: result.data.config.paySign || "",
					  	jsApiList: [
							'chooseWXPay',         // 微信支付
							'updateAppMessageShareData', // 分享到朋友圈
							'updateTimelineShareData',    // 分享给朋友
					  	]
					});
					wx.ready(() => {
						uni.showToast({
							title:'wx准备好了'
						})
						uni.hideLoading()
						wx.chooseWXPay({
							timestamp: result.data.config.timeStamp,
							nonceStr: result.data.config.nonceStr,
							package: result.data.config.package,
							signType: result.data.config.signType,
							paySign: result.data.config.paySign,
							success: (WXPayres) => {
								console.log('支付成功')
								uni.showToast({
									title: `支付成功`,
									duration: 1000
								})
								getUserInfoFun()
							},
							fail: (WXPayerror) => {
							  uni.showToast({
								title: `支付失败`,
								duration: 1000
							  })
							}
						});
					});
					wx.error((error)=>{
						console.log(error)
						uni.showToast({
							title: `${JSON.stringify(error)}`
						})
					})
				}
			})
		})
	}
	// 获取用户信息
	const getUserInfoFun = () => {
		getUserInfo().then(res=>{
			console.log(res)
			if(res.code == 1){
				userInfo.value = res.data
				uni.setStorageSync('userInfo', res.data)
			} else if (res.code == 401){
				isLoggedIn.value = false
			}
		}).catch(error=>{
			console.log(error)
		})
	}
	onMounted(()=>{
		getTianBiConfig()
	})
	onLoad( async ()=>{
		userInfo.value = uni.getStorageSync('userInfo')
		if(!uni.getStorageSync('userInfo')){
			getUserInfoFun()
		}
	})
</script>

<style scoped>
	/* Scoped styles for this page */
	/* Reusing common styles from previous pages */
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #f5f5f5;
		/* Match background color */
		padding-bottom: 40rpx;
		/* Add some padding at the bottom */
		box-sizing: border-box;
		/* Include padding in height calculation */
	}

	/* Custom Header - Styles are in CustomHeader.vue */
	/* Need padding on main content to clear fixed header */

	/* Banner Styles - Copied from previous pages */
	.banner {
		width: 100%;
		height: 300rpx;
		/* Adjust height as needed */
		position: relative;
		overflow: hidden;
	}

	.banner-bg {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}

	.banner-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 30rpx 40rpx;
		/* Adjust padding */
		color: #fff;
		/* Text color on banner */
		text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.5);
	}

	.banner-title-area {
		display: flex;
		align-items: flex-end;
	}

	.banner-main-title {
		font-size: 50rpx;
		/* Adjust font size */
		font-weight: bold;
		margin-right: 20rpx;
	}

	.banner-sub-area {
		display: flex;
		flex-direction: column;
		font-size: 24rpx;
		/* Adjust font size */
	}

	.banner-url {
		font-size: 20rpx;
		/* Adjust font size */
	}

	.banner-slogan-area {
		display: flex;
		justify-content: flex-end;
		/* Align to the right */
		font-size: 36rpx;
		/* Adjust font size */
	}

	.banner-slogan {
		margin-left: 30rpx;
		/* Spacing between slogans */
		font-weight: bold;
	}

	/* Page Title */
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		margin-top: 40rpx;
		/* Space below banner */
		margin-bottom: 30rpx;
		/* Space above main content card */
		color: #333;
	}

	/* Main Content Area (White Card) */
	.main-content {
		background-color: #fff;
		/* White background */
		margin: 0 20rpx;
		/* Side margins */
		padding: 30rpx;
		/* Inner padding */
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		/* Subtle shadow */
		display: flex;
		flex-direction: column;
		/* No align-items: center here, content is left-aligned within card */
	}

	/* Account Balance Styles */
	.account-balance {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx dashed #eee;
		/* Dashed separator */
	}

	.phone-number {
		color: #ff9800;
		/* Orange color */
		font-weight: bold;
		margin-left: 10rpx;
		margin-right: 20rpx;
	}

	.tianbi-balance {
		color: #4CAF50;
		/* Green color */
		font-weight: bold;
		margin-left: 10rpx;
	}

	.tianbi-explain {
		color: #999;
		/* Gray color */
		font-size: 24rpx;
		margin-left: 10rpx;
		text-decoration: none;
		/* Remove underline */
	}

	/* Recharge Options Styles */
	.recharge-options-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

	.recharge-options-grid {
		display: flex;
		flex-wrap: wrap;
		/* Allow items to wrap */
		justify-content: space-between;
		/* Space out items */
		margin-bottom: 30rpx;
	}

	.recharge-option {
		width: calc((100% - 30rpx) / 2);
		/* Calculate width for 2 items per row with 30rpx gap */
		height: 120rpx;
		/* Fixed height for options */
		border: 1rpx solid #ddd;
		/* Default border */
		border-radius: 8rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
		/* Space between rows */
		padding: 10rpx;
		/* Inner padding */
		box-sizing: border-box;
		/* Include border and padding in size */
	}

	.recharge-option.selected {
		border-color: #ff9800;
		/* Orange border for selected */
		background-color: #fff7e6;
		/* Light orange background for selected */
	}

	.option-main {
		font-size: 32rpx;
		/* Larger font for main text */
		font-weight: bold;
		color: red;
		/* Red color for main text */
		margin-bottom: 5rpx;
	}

	.option-bonus {
		font-size: 24rpx;
		/* Smaller font for bonus */
		color: #999;
		/* Gray color */
	}

	/* Payment Method Styles */
	.payment-method-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

	.payment-methods {
		display: flex;
		margin-bottom: 40rpx;
	}

	.payment-method-item {
		flex: 1;
		/* Allow items to take space */
		display: flex;
		align-items: center;
		justify-content: center;
		/* Center content horizontally */
		height: 80rpx;
		/* Fixed height */
		border: 1rpx solid #ddd;
		/* Default border */
		border-radius: 8rpx;
		margin-right: 20rpx;
		/* Space between items */
		position: relative;
		/* Needed for selection tick */
	}

	.payment-methods .payment-method-item:last-child {
		margin-right: 0;
		/* No margin for the last item */
	}

	.payment-method-item.selected {
		border-color: #ff9800;
		/* Orange border for selected */
		background-color: #fff7e6;
		/* Light orange background for selected */
	}

	.payment-icon {
		width: 50rpx;
		/* Icon size */
		height: 50rpx;
		margin-right: 10rpx;
	}

	.payment-text {
		font-size: 28rpx;
		color: #333;
	}

	.selection-tick {
		position: absolute;
		bottom: 0;
		right: 0;
		font-size: 30rpx;
		/* Adjust tick size */
		color: #ff9800;
		/* Orange tick color */
		/* Using text emoji ✅ as placeholder, replace with image or icon */
		/* If using an image, position it using width/height and background-image */
		transform: rotate(0deg);
		/* Adjust rotation if needed */
	}

	/* A common pattern is to use a small image for the tick icon */
	/* .selection-tick {
    position: absolute;
    bottom: -5rpx; // Adjust to overlap border
    right: -5rpx;
    width: 30rpx;
    height: 30rpx;
    background-image: url('/static/selected-tick.png'); // Replace with your image
    background-size: cover;
} */


	/* Confirm Button Styles - Orange button */
	.confirm-recharge-button {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 32rpx;
		color: #fff;
		background-color: #ff9800;
		/* Orange color */
		border: none;
		border-radius: 8rpx;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* Explanation Section */
	.explanation-section {
		margin-top: 30rpx;
		/* Space above this section */
		margin-left: 20rpx;
		/* Side margins to align with card */
		margin-right: 20rpx;
		font-size: 24rpx;
		color: #666;
		/* Gray text color */
	}

	.explanation-title {
		font-weight: bold;
		color: #ff9800;
		/* Orange color for title */
		display: block;
		/* Make title a block for margin-bottom */
		margin-bottom: 10rpx;
	}

	.explanation-text {
		display: block;
		/* Each point on a new line */
		margin-bottom: 8rpx;
		/* Space between points */
		line-height: 1.5;
		/* Improve readability */
	}


	/* QR Codes Section - Copied from previous pages */
	.qr-codes-section {
		display: flex;
		justify-content: space-around;
		padding: 40rpx 0;
		/* Vertical padding */
		margin-top: 30rpx;
		/* Space above section */
		margin-left: 20rpx;
		/* Side margins to align with card */
		margin-right: 20rpx;
	}

	.qr-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.qr-image {
		width: 200rpx;
		height: 200rpx;
		/* Need actual images */
		background-color: #eee;
		/* Placeholder background */
	}

	.qr-label {
		font-size: 26rpx;
		color: #555;
		margin-top: 10rpx;
	}

	/* Footer Styles - Copied from previous pages */
	.footer {
		margin-top: 40rpx;
		padding: 40rpx 20rpx;
		background-color: #f0f0f0;
		/* Light gray background */
		text-align: center;
		margin-top: auto;
		/* Push footer to the bottom */
		box-sizing: border-box;
	}

	.footer-links {
		font-size: 26rpx;
		color: #555;
		margin-bottom: 20rpx;
	}

	.footer-links text {
		margin: 0 10rpx;
	}

	.footer-copyright {
		font-size: 22rpx;
		color: #888;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.footer-copyright text {
		margin-bottom: 5rpx;
	}

	/* Padding to clear the fixed header */
	.page-content-wrapper {
		padding-top: 88rpx;
		/* Height of the fixed header */
		flex: 1;
		/* Allow content to take space */
		display: flex;
		flex-direction: column;
	}
</style>